package controllers

import (
	"log"
	"github.com/dgrijalva/jwt-go"
	"time"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"steam_api/models"
)


var secret_key =[]byte("steam123456")
var token_hour=time.Duration(10)  //token有效期 小时




func GetToken(uid string) (string,error) {
	otime:=time.Now()
	otime=otime.Add(time.Second*token_hour)


	var user_token =jwt.StandardClaims{ExpiresAt:otime.Unix(),Id:uid}
	token:=jwt.NewWithClaims(jwt.SigningMethodHS256,&user_token)
	tokenString, err:= token.SignedString(secret_key)
	if err != nil {
		co_log.Warning("get token %s",err)
		return "",err
	}
	return tokenString,nil
}

func CheckToken(tokenString string) bool {

	var user_token jwt.StandardClaims
	token, err := jwt.ParseWithClaims(tokenString, &user_token, func(token *jwt.Token) (interface{}, error) {
		return secret_key, nil
	})
	log.Println(token.Valid, user_token, err)
	return true
}


//func init()  {
//	token,err:=GetToken("1024")
//	log.Println(token,err)
//
//	//ii:="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTE4NTAzNTIsImp0aSI6IjEwMjQifQ.pp7RxCoX594WekFs98drwxxxSWuo3Q4Py9xJU-0q1HI"
//
//	_=CheckToken(token)
//
//
//}

type SteamToken struct {
	beego.Controller
}

type TokenMessage struct {
	Token string
	Message string
	Status int
}



// @Title token
// @Description token user into the system
// @Param	username		query 	string	true		"The username for login"
// @Param	password		query 	string	true		"The password for login"
// @Success 200 {string} login success
// @Failure 403 user not exist
// @router /gettoken [post]
func (this *SteamToken) GetToken()  {
	username:=this.GetString("username","")
	password:=this.GetString("password","")
	token_message:=new(TokenMessage)
	if username=="" || password==""{
		token_message.Message="参数不能为空"
		this.Data["json"]=token_message
		this.ServeJSON()
		return
	}

	o:=orm.NewOrm()
	user:=new(models.SteamUser)
	user.UserName=username
	user.PassWord=password
	if err:=o.Read(user,"UserName","PassWord");err!=nil{
		token_message.Message="用户名或密码错误"
		this.Data["json"]=token_message
		this.ServeJSON()
		return
	}

	new_token,_:=GetToken(string(user.Id))
	token_message.Token=new_token
	token_message.Message="获取token成功"
	token_message.Status=1
	this.Data["json"]=token_message
	this.ServeJSON()
}
